from httputils import Webrequests
from msgdata import MsgData
import json


def http_req(_msg: MsgData):
    request = Webrequests()
    method = _msg._jsonMsg.get("method")
    url = _msg._jsonMsg.get("url")
    param = _msg._jsonMsg.get("param")
    headers = _msg._jsonMsg.get("headers")
    alias = _msg._jsonMsg.get("alias")
    if method == 'get':
        rjson = request.get(url, param, headers)
        print(rjson)
        if not is_json(rjson):
            return {"result": rjson}
        return rjson
    elif method == 'post':
        rjson = request.post(url, param, headers)
        print(rjson)
        if not is_json(rjson):
            return {"result": rjson}
        return rjson
    elif method == 'post_json':
        rjson = request.post_json(url, param, headers)
        print(rjson)
        if not is_json(rjson):
            return {"result": rjson}
        return rjson


def is_json(myjson):
    if isinstance(myjson,int):
        return False
    if isinstance(myjson,float):
        return False
    if isinstance(myjson, bool):
        return False
    if isinstance(myjson,str):
        try:
            json.loads(myjson)
        except ValueError:
            return False
        return True
    if isinstance(myjson,dict):
        return True

